﻿#define STEUAW_KEYWORD

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.DirectoryServices;
using System.Globalization;
using System.Net.NetworkInformation;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Win32;

namespace SvD_Templates
{
    public partial class Form1 : Form
    {
        public int appVersion = 0;    

        private bool mostrarSeveridades = false;

        public Form1()
        {
            InitializeComponent();
            checkVersion();

            String newUpdates = "- Added the MSOM07 keyword." + Environment.NewLine + Environment.NewLine;
            newUpdates += "Please make the request to add new templates to Hector Chavez." + Environment.NewLine;
            newUpdates += Environment.NewLine + "Any question or bug please contact Jorge Limas.";


        MessageBox.Show(newUpdates,"Version Changes");
        loginForm login = new loginForm();
        login.ShowDialog();
        resetTodo();
        }

        private void checkVersion()
        {   
            FileInfo file = new FileInfo(rutaLocalApp + "/App.ver");
            try
            {
                if (file.Exists)
                {
                    StreamReader sr = new StreamReader(rutaLocalApp + "/App.ver");
                    string txtVersion = sr.ReadLine();
                    if (txtVersion != null)
                        appVersion = int.Parse(txtVersion);
                    else
                        appVersion = 0;

                    sr.Close();
                }
                else
                {
                    appVersion = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #region Function Keys
        protected override bool ProcessDialogKey(Keys keyData)
        {
            switch (keyData)
            {
                case Keys.Escape:
                    String confirmarESC = MessageBox.Show("Are you SURE you want to clean the template?", "Hey Buddy...", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
                    if (confirmarESC == "Yes")
                    {
                        resetTodo();
                        cajaTitulo.Focus();
                    }
                    break;

                case Keys.F1:
                    crearTemplateFuncion(false, null);
                    break;

                case Keys.F4:
                    pasteClipboardURL();
                    break;

                case Keys.F2:
                    if (comboIdioma.SelectedIndex == 1)
                        comboIdioma.SelectedIndex = 2;
                    else
                        comboIdioma.SelectedIndex = 1;
                    break;


                case Keys.F3:
                    if (!mostrarSeveridades)
                    {
                        this.Width = 970;
                        mostrarSeveridades = true;
                    }
                    else
                    {
                        this.Width = 700;
                        mostrarSeveridades = false;
                    }
                    break;
            }

            return base.ProcessDialogKey(keyData);
        } 
        #endregion

        

        #region Preguntas de Severidad
        
       

        #endregion

        private void crearTemplateFuncion(bool guardarTemplate, string pathGuardar)
        {
            try
            {
                datosTemplate temp = new datosTemplate();
                Template Template = new Template();

                // Titulo del ticket
                temp.Titulo = cajaUbicacion.Text + ", " + cajaTitulo.Text;

                // User Company
                // temp.user_Company = cajaCompania.Text;
                // Cambiarlo a Combo Box - temp.Severidad = comboSeveridad.SelectedItem.ToString();
                temp.user_Company = comboCompany.SelectedItem.ToString();


                // Verificar Asset
                if (checkAsset.Checked && rCheckAssetSi.Checked)
                    temp.Verificar_Asset = "Yes, Asset Validated on Service Center";
                else if (checkAsset.Checked && rCheckAssetNo.Checked)
                    temp.Verificar_Asset = "No, ASSET WAS NOT FOUND IN AC, PLEASE VALIDATE ASSET";
                if (!checkAsset.Checked)
                    temp.Verificar_Asset = "No";

                // Verificar SSN o RFC
                if (checkSSNRFC.Checked) temp.Verificar_SSNRFC = "Yes";
                else temp.Verificar_SSNRFC = "No";

                // es un IMAC?
                if (checkIMAC.Checked) temp.Es_IMAC = "Yes";
                else temp.Es_IMAC = "No";

                // Idioma
                temp.Idioma = comboIdioma.SelectedItem.ToString();

                // KeyWord
                if (cajaKeyword.Text == "") temp.Keyword = "N/A";
                else temp.Keyword = cajaKeyword.Text;

                // Detalles del ticket (Issue)
                temp.Detalles_Ticket = cajaDetallesTicket.Text;

                // Acciones Realizadas (TroubleShooting)
                temp.Acciones_Realizadas = cajaAcciones.Text;

                // Caja a Asignar (Dispatching)
                if (cajaDespacho.Text == "") temp.Caja_Asignacion = "No";
                else temp.Caja_Asignacion = cajaDespacho.Text;

                // Severidad
                temp.Severidad = comboSeveridad.SelectedItem.ToString();

                // Mejor hora para localizar al Usuario
                if (cajaHoraLocalizar.Text == "") temp.Mejor_Hora_Localizar = "N/A";
                else temp.Mejor_Hora_Localizar = cajaHoraLocalizar.Text;

                // Contacto Alterno o Telefono Alterno
                if (cajaContactoAlterno.Text == "") temp.Contact_Alterno = "N/A";
                else temp.Contact_Alterno = cajaContactoAlterno.Text;

                // Warm Transfer
                if (cajaWarmTransfer.Text == "") temp.Warm_Transfer = "No";
                else temp.Warm_Transfer = cajaWarmTransfer.Text;

                // Template adicional
                temp.templateAdicional = cajaTemplateAdicional.Text;

                // Informacion Extra
                temp.infoExtra = cajaInfoExtra.Text;

                // URL
                String _no_url = "Yes";
                if (cajaURL.Text == "")
                {
                    _no_url = MessageBox.Show("You are creating a template without URL.\nThis could lead to a mishandled case.\n\nDo you wish to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning).ToString();
                    temp.url = "";//"http://ekmswgi.amer.quick2know.eds.com/EKMS/WGI_Delphi_US/";
                }
                else temp.url = cajaURL.Text;

                // Ticket Otorgado
                if (checkTicket.Checked) temp.Ticket_Otorgado = "Yes";
                else temp.Ticket_Otorgado = "No, " + cajaTicket.Text;


                // Severity Questions
                // Shipments
                if (cajaShipments1.Text == "") temp.SQ_Shipments_1 = "N/A";
                else temp.SQ_Shipments_1 = cajaShipments1.Text;

                if (cajaShipments2.Text == "") temp.SQ_Shipments_2 = "N/A";
                else temp.SQ_Shipments_2 = cajaShipments2.Text;

                if (cajaShipments3.Text == "") temp.SQ_Shipments_3 = "N/A";
                else temp.SQ_Shipments_3 = cajaShipments3.Text;

                // Manufacturing
                if (cajaManufacturing1.Text == "") temp.SQ_Manufacturing_1 = "N/A";
                else temp.SQ_Manufacturing_1 = cajaManufacturing1.Text;

                if (cajaManufacturing2.Text == "") temp.SQ_Manufacturing_2 = "N/A";
                else temp.SQ_Manufacturing_2 = cajaManufacturing2.Text;

                if (cajaManufacturing3.Text == "") temp.SQ_Manufacturing_3 = "N/A";
                else temp.SQ_Manufacturing_3 = cajaManufacturing3.Text;

                // Business
                if (cajaBusiness1.Text == "") temp.SQ_Business_1 = "N/A";
                else temp.SQ_Business_1 = cajaBusiness1.Text;

                if (cajaBusiness2.Text == "") temp.SQ_Business_2 = "N/A";
                else temp.SQ_Business_2 = cajaBusiness2.Text;

                if (cajaBusiness3.Text == "") temp.SQ_Business_3 = "N/A";
                else temp.SQ_Business_3 = cajaBusiness3.Text;
                

                // Outage
                if (cajaOutage1.Text == "") temp.SQ_Outage_1 = "N/A";
                else temp.SQ_Outage_1 = cajaOutage1.Text;

                if (cajaOutage2.Text == "") temp.SQ_Outage_2 = "N/A";
                else temp.SQ_Outage_2 = cajaOutage2.Text;

                if (cajaOutage3.Text == "") temp.SQ_Outage_3 = "N/A";
                else temp.SQ_Outage_3 = cajaOutage3.Text;
               

                // Other
                if (cajaOther1.Text == "") temp.SQ_Other_1 = "N/A";
                else temp.SQ_Other_1 = cajaOther1.Text;

                if (cajaOther2.Text == "") temp.SQ_Other_2 = "N/A";
                else temp.SQ_Other_2 = cajaOther2.Text;

                if (cajaOther3.Text == "") temp.SQ_Other_3 = "N/A";
                else temp.SQ_Other_3 = cajaOther3.Text;
                

                if (guardarTemplate)
                {
                    Template.crearTextoTemplate(temp, pathGuardar);
                }

                if (!guardarTemplate && _no_url != "No")
                {
                    Template.CrearTemplate(temp);                        
                    this.WindowState = FormWindowState.Minimized;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Verifica que esten completos los campos: Severidad e Idioma" + Environment.NewLine + Environment.NewLine + "Error: " + Environment.NewLine + ex.Message, "Error");
            }

            loadTemplates();

        }

        private void label4_Click(object sender, EventArgs e)
        {
            cajaDetallesTicket.Text = cajaTitulo.Text;
        }

        private void resetTodo()
        {
            cajaTitulo.ResetText();
            cajaUbicacion.ResetText();
            comboCompany.SelectedItem = (Object)"Delphi";
            checkAsset.Checked = false;
            checkSSNRFC.Checked = false;
            checkIMAC.Checked = false;
            comboIdioma.SelectedIndex = 1;
            comboTemplate.SelectedItem = (Object)"";
            comboKeywords.SelectedItem = (Object)"";
            comboMiniTemplates.SelectedItem = (Object)"";
            cajaKeyword.ResetText();
            cajaDetallesTicket.ResetText();
            cajaAcciones.ResetText();
            cajaDespacho.ResetText();
            cajaHoraLocalizar.ResetText();
            cajaWarmTransfer.ResetText();
            comboSeveridad.SelectedItem = (Object)"4";
            cajaTemplateAdicional.ResetText();
            cajaInfoExtra.ResetText();
            cajaTicket.ResetText();
            cajaURL.ResetText();

            comboTimeZones.SelectedItem = (Object)"";
            comboKeywords.SelectedItem = (Object)"";

            #region Preguntas de Severidad
            cajaShipments1.ResetText();
            cajaShipments2.ResetText();
            cajaShipments3.ResetText();

            cajaManufacturing1.ResetText();
            cajaManufacturing2.ResetText();
            cajaManufacturing3.ResetText();

            cajaBusiness1.ResetText();
            cajaBusiness2.ResetText();
            cajaBusiness3.ResetText();

            cajaOutage1.ResetText();
            cajaOutage2.ResetText();
            cajaOutage3.ResetText();

            cajaOther1.ResetText();
            cajaOther2.ResetText();
            cajaOther3.ResetText();

            this.Width = 700;
            #endregion
          
            cajaContactoAlterno.ResetText();
        }

        private void pasteClipboardURL()
        {
            string urlTest = Clipboard.GetText();

            if (urlTest.Contains("http"))
            {
                cajaURL.Text = urlTest;
            }
            else MessageBox.Show("No tienes una URL valida en el Clipboard");
        }

        private void clipboardPaste_Click(object sender, EventArgs e)
        {
            pasteClipboardURL();
        }


        #region Obtener Templates del Servidor

        private string rutaServidor = @"\\192.85.87.68\Shortkeys\Templates";
        private string rutaLocal = @"C:\Program Files\SvD Templates\Templates";
        private string rutaServidorApp = @"\\192.85.87.68\Shortkeys\App";
        private string rutaLocalApp = @"C:\Program Files\SvD Templates\App";
        private string rutaLocalTemp = @"C:\Program Files\SvD Templates\Temp";
        private string nomArchivo, destArchivo;

        private void getTemplatesFromServer()
        {
            if (Directory.Exists(rutaServidor))
            {
                // Verificar si existe el folder local
                if (!Directory.Exists(rutaLocal))
                    Directory.CreateDirectory(rutaLocal);
                
                // Limpiar el folder local
                DirectoryInfo dir = new DirectoryInfo(rutaLocal);
                foreach (FileInfo file in dir.GetFiles())
                {                   
                    file.Delete();
                }
                
                // Pasar los archivos
                string[] files = Directory.GetFiles(rutaServidor);
                foreach (string s in files)
                {
                    nomArchivo = Path.GetFileName(s);
                    destArchivo = Path.Combine(rutaLocal, nomArchivo);
                    File.Copy(s, destArchivo, true);
                }
            }
            else
            {
                Console.WriteLine("Servidor no disponible!");
            }

        }        

        #endregion

        #region Cargar Templates
        private void loadTemplates()
        {
            // Mini Templates TXT
            comboMiniTemplates.Items.Clear();
            comboMiniTemplates.Items.Add("");

            try
            {
                DirectoryInfo Dir = new DirectoryInfo(rutaLocal);
                FileInfo[] FileList = Dir.GetFiles("*.txt", SearchOption.AllDirectories);

                foreach (FileInfo FI in FileList)
                {
                    string[] name = FI.Name.Split('.');
                    comboMiniTemplates.Items.Add(name[0]);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            // Templates INI
            comboTemplate.Items.Clear();
            comboTemplate.Items.Add("");
            try
            {
                DirectoryInfo Dir = new DirectoryInfo(rutaLocal);
                FileInfo[] FileList = Dir.GetFiles("*.ini", SearchOption.AllDirectories);

                foreach (FileInfo FI in FileList)
                {
                    string[] name = FI.Name.Split('.');
                    comboTemplate.Items.Add(name[0]);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void setCurrentVersionFile()
        {
            FileStream file = new FileStream(rutaLocalApp + "/App.ver", FileMode.Create, FileAccess.Write);
            TextWriter tw = new StreamWriter(file);
            tw.Write(appVersion.ToString());
            tw.Close();            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                this.Hide();
                comboSeveridad.SelectedIndex = 2;
                comboIdioma.SelectedIndex = 1;
                this.Width = 700;
                this.Text = "SvD Templates - Delphi Agents Version 1." + appVersion.ToString();

                //CENTER
                int oldX = this.Location.X;
                this.Location = new Point(oldX + 158, this.Location.Y);

                setCurrentVersionFile();

                MessageBox.Show("Downloading templates.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                getTemplatesFromServer();
                loadTemplates();
                MessageBox.Show("Templates loaded.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Show();

                crearNuevoTemplateToolStripMenuItem.Visible = false;
                timer1.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }

        private void comboMiniTemplates_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string nombre = comboMiniTemplates.SelectedItem.ToString();
                if (nombre != "")
                {
                    TextReader tr = new StreamReader(rutaLocal + "\\" + nombre + ".txt");
                    if (cajaTemplateAdicional.Text != "")
                        cajaTemplateAdicional.Text += Environment.NewLine;
                    cajaTemplateAdicional.Text += tr.ReadToEnd();

                    tr.Close();
                }
                else
                {
                    cajaTemplateAdicional.Text = "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void comboTemplate_SelectedIndexChanged(object sender, EventArgs e)
        {         
            try
            {

                string nombre = comboTemplate.SelectedItem.ToString();
                if (nombre != "")
                {
                    resetTodo();

                    INI ini = new INI(rutaLocal + "\\" + nombre + ".ini");

                    cajaTitulo.Text = ini.IniReadValue("temp", "titulo");

                    if (ini.IniReadValue("temp", "verificaste_SSNRFC").ToLower() == "yes")
                        checkSSNRFC.Checked = true;

                    if (ini.IniReadValue("temp", "esIMAC").ToLower() == "yes")
                        checkIMAC.Checked = true;

                    if (ini.IniReadValue("temp", "verificaste_Asset").ToLower() == "yes")
                        checkAsset.Checked = true;

                    cajaKeyword.Text = ini.IniReadValue("temp", "keyword");
                    comboIdioma.SelectedItem = (Object)ini.IniReadValue("temp", "idioma");
                    cajaDetallesTicket.Text = ini.IniReadValue("temp", "detalles_problema");
                    cajaAcciones.Text = ini.IniReadValue("temp", "acciones_realizadas");
                    cajaDespacho.Text = ini.IniReadValue("temp", "caja_despacho");
                    cajaURL.Text = ini.IniReadValue("temp", "url");
                    comboSeveridad.SelectedItem = (Object)ini.IniReadValue("temp", "severidad");
                }
                else
                {
                    resetTodo();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void recargarTemp_Click(object sender, EventArgs e)
        {
            loadTemplates();
            resetTodo();
        }

        private void checkIMAC_CheckedChanged(object sender, EventArgs e)
        {
            if (checkIMAC.Checked)
            {
                comboSeveridad.SelectedIndex = 1;
                cajaKeyword.Text = "IMAC";
            }
            else
            {
                cajaKeyword.ResetText();
                comboSeveridad.SelectedIndex = 2;
            }
        }    

        private void checkAsset_CheckedChanged(object sender, EventArgs e)
        {
            if (checkAsset.Checked)
            {
                rCheckAssetSi.Visible = true;
                rCheckAssetNo.Visible = true;
            }
            else
            {
                rCheckAssetSi.Visible = false;
                rCheckAssetNo.Visible = false;
            }
        }

        private void quickTextGroup(string nomCorto, string nomCaja, int sev, string url)
        {
            if (cajaDespacho.Text == nomCorto || cajaDespacho.Text == nomCaja)
            {
                try
                {
                    cajaDespacho.Text = nomCaja + " ";
                    string nombre = nomCorto;
                    if (nombre != "")
                    {
                        TextReader tr = new StreamReader(rutaLocal + "/" + nombre + ".txt");
                        if (cajaTemplateAdicional.Text != "")
                            cajaTemplateAdicional.Text += Environment.NewLine;
                        cajaTemplateAdicional.Text += tr.ReadToEnd();

                        tr.Close();

                        if(sev != 0)
                            comboSeveridad.SelectedItem = (Object)sev.ToString();
                        cajaURL.Text = url;
                    }
                    else
                    {
                        cajaTemplateAdicional.Text = "";
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void cajaDespacho_TextChanged(object sender, EventArgs e)
        {
            quickTextGroup("HP", "DELP_HP_DISPATCH", 0, null);
            quickTextGroup("EPS", "DELP_LEPS", 3, "http://ekmswgi.amer.quick2know.eds.com/ekms/wgi_delphi_mexico/02IM/02Resolve/SD/E/EPS/General/eps.htm");
            quickTextGroup("RDM", "DELP_SMC_CLIENT_MX", 0, null);
            quickTextGroup("TELMEX", "DELP_TELMEX", 0, null);
            quickTextGroup("VOICE", "DELP_AMER_VOICE", 0, null);
        }  

        private void recargarLosTemplatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            getTemplatesFromServer();
            loadTemplates();
            resetTodo();
        }

        private void crearNuevoTemplateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.RestoreDirectory = true;
            dialog.InitialDirectory = rutaServidor;
            dialog.Filter = "Archivos Template (*.INI) | *.INI";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string path = dialog.FileName;
                if (dialog.CheckPathExists)
                {                   
                    crearTemplateFuncion(true, path);
                }
            }
            
            dialog.Dispose();
        }

        private void salirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Deseas cerrar la aplicacion?", "Alerta", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString() == "Yes")
            {
                Application.Exit();
            }
        }

        private void networToolStripMenuItem_Click(object sender, EventArgs e)
        {
            netTools net = new netTools();
            net.Show();
        }

        private void soporteEnSitioToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void herramientasDeActiveDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            adTools ad = new adTools();
            ad.Show();
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState && minTrayOpt.Checked)
            {
                Hide();
            }
        }

        private void SystemTray_DoubleClick(object sender, EventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            netTools net = new netTools();
            net.Show();
        }

        private void activeDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            adTools ad = new adTools();
            ad.Show();
        }

        private void cerrarLaApplicacionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Deseas cerrar la aplicacion?", "Alerta", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString() == "Yes")
            {
                Application.Exit();
            }
        }

        #region Registro de HotKey

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam,
           IntPtr lParam);

        public IntPtr FindWindow(string wndName)
        {
            return FindWindow(null, wndName);
        }

        KeyboardHook hook = new KeyboardHook();
        void hook_KeyPressed(object sender, KeyPressedEventArgs e)
        {
        }

        public void registrarHotkey()
        {
            try
            {
                hook.KeyPressed +=
                    new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);

                hook.RegisterHotKey(Win32.ModifierKeys.Alt, Keys.Insert);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        } 

        #endregion

        private void minTrayOpt_Click(object sender, EventArgs e)
        {
            if (minTrayOpt.Checked == true)
                minTrayOpt.Checked = false;
            else
                minTrayOpt.Checked = true;
        }

        private void checkTicket_CheckedChanged(object sender, EventArgs e)
        {
            if (!checkTicket.Checked)
            {
                cajaTicket.Visible = true;
                cajaTicket.ResetText();
            }
            else
            {
                cajaTicket.Visible = false;
                cajaTicket.ResetText();
            }
        }

        private void comboKeywords_SelectedIndexChanged(object sender, EventArgs e)
        {
            cajaKeyword.Text = comboKeywords.SelectedItem.ToString();
            
                if (cajaKeyword.Text == "STEUAW")
                {
                    cajaTitulo.Text += ", STEUAW";
                    cajaKeyword.ResetText();
                }   

                if (cajaKeyword.Text == "XEROX")
                {
                    cajaTitulo.Text += ", XEROX";
                    cajaKeyword.ResetText();
                }

                if (cajaKeyword.Text == "MSOM07")
                {
                    cajaTitulo.Text += ", MSOM07";
                    cajaKeyword.ResetText();
                }
        }

        private void comboTimeZones_SelectedIndexChanged(object sender, EventArgs e)
        {
            cajaHoraLocalizar.Text += " " + comboTimeZones.SelectedItem.ToString();
        }

        public int avisosActualizaciones = 0;

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                // Verificar si existe el folder local
                if (!Directory.Exists(rutaLocalTemp))
                {
                    Directory.CreateDirectory(rutaLocalTemp);
                }

                // Limpiar el folder local
                DirectoryInfo dir = new DirectoryInfo(rutaLocalTemp);
                foreach (FileInfo file in dir.GetFiles())
                {
                    file.Delete();
                }

                // Pasar los archivos
                string[] files = Directory.GetFiles(rutaServidorApp);
                foreach (string s in files)
                {
                    nomArchivo = Path.GetFileName(s);
                    destArchivo = Path.Combine(rutaLocalTemp, nomArchivo);
                    File.Copy(s, destArchivo, true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error Controlado", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            int serverVersion = 0;
            int localVersion = 0;

            StreamReader sr = new StreamReader(rutaLocalTemp + "/App.ver");
            string txtVersion = sr.ReadLine();
            serverVersion = int.Parse(txtVersion);

            if (File.Exists(rutaLocalApp + "/App.ver"))
            {
                StreamReader sr2 = new StreamReader(rutaLocalApp + "/App.ver");
                txtVersion = sr2.ReadLine();
                localVersion = int.Parse(txtVersion);
                sr2.Close();
            }
            else
                localVersion = 0;

            sr.Close();

            if (serverVersion != localVersion)
            {
                if(avisosActualizaciones < 3)
                {
                    avisosActualizaciones++;
                    String mensaje = "Existe una version mas nueva de la aplicacion." + Environment.NewLine;
                    mensaje += "Favor de cerrar la aplicacion para recibir la actualizacion." + Environment.NewLine;
                    mensaje += "Este es el aviso " + avisosActualizaciones.ToString() + " de 3" + Environment.NewLine + Environment.NewLine;
                    mensaje += "Al tercer aviso la aplicacion se cerrara automaticamente.";
                    MessageBox.Show(mensaje, "Actualizacion Disponible", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else Application.Exit();
            }
            else
            {
                
            }
        }

        private void comboCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            String _company = comboCompany.SelectedItem.ToString();

            if (_company == "Nexteer" || _company == "GMCH")
            {
                cajaTitulo.Text += ", STEUAW";
            }

            if (_company == "BWI")
            {
                cajaTitulo.Text += ", BWI";
            }
        }

        private void askRDMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String _resp = MessageBox.Show("This will send a question to the RDM team, if someone is available you should receive a reply within 3 minutes." + Environment.NewLine + Environment.NewLine + "Do you have this time?", "RDM Team", MessageBoxButtons.YesNo, MessageBoxIcon.Information).ToString();
            
            if (_resp == "Yes")
            {
                askRDM rdm_ = new askRDM();
                rdm_.ShowDialog();
            }

        }        
    }


}
